
import os
import datetime
import tkinter.filedialog
import tkinter.messagebox
from   tkinter import *


class FilesName:
    def LogFilesNames(self):
        NowTime = datetime.datetime.now()
        NowTime_year = (str(NowTime.year))
        NowTime_month = (str(NowTime.month))
        NowTime_day = (str(NowTime.day))
        NowTime_hour = (str(NowTime.hour))
        NowTime_minute = (str(NowTime.minute))
        return  NowTime_year + NowTime_month + NowTime_day + NowTime_hour + NowTime_minute


from LogFilesName import FilesName

class SeachLogFiles:

    def SeachLog(self,FileName_input,KeyWord_input):

        DateForFileName = FilesName() #实例化时间字符串类
        FileNameII = str(DateForFileName.LogFilesNames())+".log" #拼接字符串为文件名称

        FileName = FileName_input
        InputData = KeyWord_input

        fileI = open(FileName,'r+',encoding = 'utf-8') #打开目标文件
        FolderName = InputData+"_"+FileNameII #确定文件夹名称
        os.mkdir(FolderName) #创建文件夹
        fileII = open(FolderName+"/"+InputData+".log",'w+',encoding = 'utf-8') #创建并且打开文件

        for line in fileI:
            line = line.strip()

            if not len(line) or line.startswith('#'):
                continue

            if InputData in line:
                fileII.writelines(line)
                fileII.writelines("\n")

        fileII.close()
        fileI.close()

        return "Doing ok"

filename = ""


def doingn():
    DoingNow = SeachLogFiles()
    DoingNow.SeachLog(var.get(),varkeyword.get())
    l = Label(frm_R, text="Do ok", bg="red", font=("Arial", 12), width=5, height=2)
    l.pack(side=BOTTOM)  # 这里的side可以赋值为LEFT  RTGHT TOP  BOTTOM

def get_file():
    global filename

    filename = tkinter.filedialog.askopenfilename(filetypes=[("text file", "*.log")])
    var.set(filename)

if __name__ == '__main__':

    # 创建根窗口
    root = Tk()
    root.title("Log文件检索工具")
    root.geometry("400x200+450+210")  # width x height;起始坐标


    frame = Frame(root)
    frame.pack()

    frm_L = Frame(frame)
    var = StringVar()
    var.set("请选择文件")  # 设置文本框中的值
    varkeyword = StringVar()
    varkeyword.set("请输入关键字")  # 设置文本框中的值

    Label(frm_L, text="").pack()
    Entry(frm_L, textvariable=var, bd=1,width=25).pack(expand=1)
    Entry(frm_L, textvariable=varkeyword, bd=1,width=25).pack(expand=1)

    Label(frm_L, text="").pack()
    frm_L.pack()

    frm_R = Frame(frame)
    Button(frm_R, text="选择文件", command=get_file, height=2, width=8).pack(side=LEFT)
    Button(frm_R, text="生成文件", command=doingn, height=2, width=10).pack(side=RIGHT)
    frm_R.pack()

    frm_D = Frame(root)
    Button(frm_D, text="退出", command=frm_R.quit, height=2, width=8, bg="#B0D060").pack()
    frm_D.pack(side=BOTTOM)

    root.mainloop()